package com.loan.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loan.common.core.domain.PageQuery;
import com.loan.common.core.page.TableDataInfo;
import com.loan.common.enums.PayCompanyEnum;
import com.loan.common.exception.ServiceException;
import com.loan.common.pay.hqpay.HQPayUtils;
import com.loan.common.utils.StringUtils;
import com.loan.system.domain.CompanyEntity;
import com.loan.system.domain.PayConfigEntity;
import com.loan.system.mapper.PayConfigMapper;
import com.loan.system.service.PayConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author shiguang
 * @date 2022年09月21日 23:43
 */
@Service
@RequiredArgsConstructor
public class PayConfigServiceImpl implements PayConfigService {

    private final PayConfigMapper payConfigMapper;

    @Override
    public TableDataInfo<PayConfigEntity> selectPageList(PayConfigEntity entity, PageQuery pageQuery) {
        Map<String, Object> params = entity.getParams();
        LambdaQueryWrapper<PayConfigEntity> lqw = new LambdaQueryWrapper<PayConfigEntity>()
                .like(StringUtils.isNotBlank(entity.getName()), PayConfigEntity::getName, entity.getName())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        PayConfigEntity::getCreateTime, params.get("beginTime"), params.get("endTime"));
        Page<PayConfigEntity> page = payConfigMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addPayConfig(PayConfigEntity entity) {
        //如果为hqpay  则登录获取token
        if (entity.getPayCompany().equals(PayCompanyEnum.HQ_PAY.getCode())){
            loginHqpay(entity);
        }
        int count = payConfigMapper.insert(entity);
        return count;
    }

    @Async
    public void loginHqpay(PayConfigEntity entity){
        String result = HQPayUtils.login(entity.getMercharntId(), entity.getAppId());
        JSONObject jsonObject = JSONObject.parseObject(result);
        String tokenType = jsonObject.getJSONObject("data").getString("token_type");
        String accessToken = jsonObject.getJSONObject("data").getString("access_token");
        if (StringUtils.isNotBlank(tokenType) && StringUtils.isNotBlank(accessToken)){
            String token = tokenType + " " + accessToken;
            entity.setHqpayToken(token);
            payConfigMapper.updateById(entity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePayConfig(PayConfigEntity entity) {
        PayConfigEntity configEntity = payConfigMapper.selectById(entity.getId());
        if (!configEntity.getMercharntId().equals(entity.getMercharntId()) ||  !configEntity.getAppId().equals(entity.getAppId())){
            if (entity.getPayCompany().equals(PayCompanyEnum.HQ_PAY.getCode())){
                loginHqpay(entity);
            }
        }else if (StringUtils.isBlank(configEntity.getHqpayToken())){
            loginHqpay(entity);
        }
        return payConfigMapper.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteConfigById(Long id) {
        return payConfigMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStatus(PayConfigEntity entity) {
        return payConfigMapper.updateById(entity);
    }

    @Override
    public PayConfigEntity selectPayConfigById(Long id) {
        return payConfigMapper.selectById(id);
    }

    @Override
    public List<PayConfigEntity> selectList() {
        return payConfigMapper.selectList(new QueryWrapper<PayConfigEntity>().eq("status","0").eq("del_flag","0").orderByAsc("id"));
    }
}
